package com.bytecodezz.app.base.widget.draw

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.bytecodezz.app.base.widget.R

class DrawGridView(
    context: Context?,
    attrs: AttributeSet?,
    defStyleAttr: Int,
    defStyleRes: Int
) : View(context, attrs, defStyleAttr, defStyleRes) {

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        0,
        0
    )

    private var interval: Int = 45
    private var lineSize: Float = 0.5f
    private var lineColor: Int = Color.parseColor("#ffffff")
    private var linePaint: Paint = Paint()

    init {
        attrs?.let {
            val ta = context!!.obtainStyledAttributes(it, R.styleable.DrawGridView)
            lineSize = ta.getDimension(R.styleable.DrawGridView_line_size, lineSize)
            interval = ta.getInteger(R.styleable.DrawGridView_line_interval, interval)
            lineColor = ta.getColor(R.styleable.DrawGridView_line_color, lineColor)
            ta.recycle()
        }
        linePaint.color = lineColor
        linePaint.strokeWidth = lineSize
        linePaint.isAntiAlias = true
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onDraw(canvas: Canvas) {
        for (x in 0..measuredWidth step interval) {
            canvas.drawLine(
                x.toFloat(),
                0.toFloat(),
                x.toFloat(),
                measuredHeight.toFloat(),
                linePaint
            )
        }
        for (y in 0..measuredHeight step interval) {
            canvas.drawLine(
                0.toFloat(),
                y.toFloat(),
                measuredWidth.toFloat(),
                y.toFloat(),
                linePaint
            )
        }
    }

}